/**
	Copyright (c) 2009 Ozazo Pvt Ltd, INDIA

	Permission is hereby granted, free of charge, to any person or organization 
	obtaining a copy of this software and associated  documentation  files (the 
	"Software"), to deal in the Software without restriction, including without 
	limitation the rights to use, copy, modify, merge, publish, distribute, sub
	license, and/or sell copies of the Software, and to permit persons  to whom 
	the Software is furnished to do so, subject to the following conditions:
	
	The above copyright notice and  this permission notice shall be included in 
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS",  WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING  BUT NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY,  WHETHER  IN  AN  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
	FROM,  OUT  OF  OR  IN  CONNECTION  WITH  THE  SOFTWARE OR THE USE OR OTHER 
	DEALINGS IN THE SOFTWARE
 */

package com.ozazo.wave.robots.engines;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import com.google.wave.api.Annotation;
import com.google.wave.api.Blip;
import com.google.wave.api.Image;
import com.google.wave.api.Range;
import com.google.wave.api.TextView;
import com.ozazo.wave.robots.fw.engines.RobotEngineInterface;
import com.ozazo.wave.robots.fw.engines.Commands;
import com.ozazo.wave.robots.fw.search.OpenSearchResult;

/**
 * @author Araf Karsh Hamid
 * @version 1.0
 * @seriel 20091121102030
 *
 */
public class LateXEngine implements RobotEngineInterface {
	
	private final Logger log;

	private String lateXURL 			= "http://sciencesoft.at/image/latexurl/image.png?src=%s";
	private String searchQuery 			= "\\sum_{n=09}^{+\\infty}\\frac{9}{s^2}=\\frac{\\pi^2}{23}";	
	private boolean isModified 			= false;
	
	private final String regexCommands	= "(?ism)[-/](w|wd|ltx)\\b";
	
	public LateXEngine() {
		this(Logger.getLogger("LaTeXEngine"));
	}
	
	public LateXEngine(Logger _log) {
		log = _log;
	}
	
	/**
	 * Set the Search Query. Query String can be of single word or multiple words.
	 * 
	 * @param _searchQuery
	 */
	public void setSearchQuery(final String _searchQuery) {
		if( (_searchQuery != null) && (!_searchQuery.trim().equals("")) ) {
			searchQuery = _searchQuery;
		}	
	}
	
	public String getSearchQuery() {
		return searchQuery;
	}
	
	/**
	 * Get the Query String to search.
	 * 
	 * @return String
	 */

	private String getServerURL() {
		return String.format(lateXURL, searchQuery);
	}	
	/**
	 * From the list of String Tokens - Create the Search URL and returns valid
	 * commands List.
	 *
	 * @param List<Commands>
	 * @return List<Commands>
	 */	
	
	public List<Commands> processCommands(List<Commands> _list) {
		List<Commands> cmdList = new ArrayList<Commands>();
		if(_list == null) {
			return cmdList;
		}
		for(Commands cmd : _list) {
			if(cmd.getCommand().equalsIgnoreCase("ltx"))  {
				String qry = cmd.getValue();	
				setSearchQuery(qry);
				// This section to get the URL needs to be replaced with REST API Calls
				// Second version of the LaTeX Engine will contain REST API calls
				String url = this.getServerURL();
				if( (this.getSearchQuery() != null) && (!getSearchQuery().trim().equals("")) ) {
					// With REST API calls the hard coded image size will be removed
					cmd.setExternalData(new Image(url, 160,30, cmd.getValue()));
					cmdList.add(cmd);
				}			
			}
		}		
		return cmdList;
	}

	/**
	 * This method illustrates how to replace the text in Blip without using TextView.replace(String) method.
	 * The replace method looses all the styles and annotations of the TextView. This method uses the following functionality
	 * from the TextView object in the Google Wave.
	 * 
	 * 1. Uses Range and Annotations to insert the text in the right place.
	 * 2. Uses Annotations to create hyper links.
	 * 3. Uses replace with range parameter to edit specific substring of the text in the TextView.
	 * 4. Uses delete method to remove text from the Blip
	 * 
	 * @param Blip _blip
 	 * @param List<Commands> dataMap
	 */	
	
	public void processBlip(Blip _blip, List<Commands> dataMap) {
		if( (_blip == null) || (_blip.getDocument().getText().trim().equals("")))  {
			return;
		}
		if(dataMap == null) {
			return;
		}
		TextView txtView = _blip.getDocument();	
		for(Commands cmds : dataMap) {
			if(cmds != null) {
				Image formula = (Image) cmds.getExternalData();				
				if(formula != null) {
					int sRange = txtView.getText().indexOf(cmds.getText());
					if(sRange <0) {
						log.severe("|sRange="+sRange+"|Txt="+cmds.getText());
						// log.severe("|Blip="+txtView.getText());
						sRange = 0;
					}
					int eRange = sRange + cmds.getText().length();
					try {
						Range txtRange = new Range(sRange, eRange);
						// txtView.replace(txtRange, "");
						txtView.delete(txtRange);
					} catch (Exception i) {
						log.severe("|Txt="+cmds.getText()+"|"+i.getMessage());
						i.printStackTrace();
					}
					txtView.insertElement(sRange, formula);
				}
			}
		}
	}	
	
	/**
	 * Process the text. The Original message will be processed in this step.
	 * All the commands (/ltx) will be removed and the Tokens will be replace with
	 * Token + LateX image Object.
	 * 
	 * An updated new Text will be returned.
	 *
	 * @return String text
	 */

	public String processText(String text, List<Commands> dataMap) {
		String newText = text;
		isModified = false;
		if(text != null){
			newText = text.replaceAll(regexCommands, "");
			if( dataMap != null) {
				for(Commands cmds : dataMap) {
					if(cmds != null) {
						Image image = (Image) cmds.getExternalData();
						newText = newText.replace(cmds.getOriginalValue(), image.getUrl());
						log.info("LateXEngine> Image.URLS> "+ image.getUrl());
						isModified = true;
					}
				}
			}
		}
		return newText;
	}	
	
}
